package web.java.b_DBCP;

import static org.junit.Assert.*;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;




import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;

/**
 * 使用DBCP组件来实现连接池
 * */
public class DBCP {
	/**
	 * 1、硬编码实现连接池
	 * 	核心类：BasicDataSource
	 * */
	@Test
	public void testBasic() throws Exception {
		//创建BasicDataSource对象
		BasicDataSource dataSource=new BasicDataSource();
		/*
		 * 连接池设置参数
		 * URL，username，password
		 * 默认连接数，最大连接数
		 * */
		dataSource.setUrl("jdbc:mysql://localhost:3306/shop");
		//dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setInitialSize(3);	//默认连接数
		dataSource.setMaxActive(6);	//最大连接数
		dataSource.setMaxIdle(3000);	//最大空闲时间，超过时间自动关闭
		//创建连接
		Connection conn1=dataSource.getConnection();
		String sql="delete from emp where emp_id=21";
		Statement stmt=conn1.createStatement();
		int result=stmt.executeUpdate(sql);
		System.out.println(result);
		conn1.close();
	}
	/**
	 * 2、配置方式实现连接池
	 * 	  核心工具类：BasicDataSourceFactory
	 *   核心接口：DataSource BasicDataSourceFactory.createDataSource(Properties prop);
	 * */
	@Test
	public void testProps() throws Exception {
		//加载数据库配置文件
		InputStream in=DBCP.class.getResourceAsStream("db.properties");
		Properties props=new Properties();
		props.load(in);
		//创建连接池
		DataSource dataSource=BasicDataSourceFactory.createDataSource(props);
		Connection conn=dataSource.getConnection();
		String sql="delete from emp where emp_id=22";
		Statement stmt=conn.createStatement();
		int result=stmt.executeUpdate(sql);
		System.out.println(result);
		conn.close();
	}
}
